<template>
  <div class="my-notes">
    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="class" tab="课堂笔记">
        <div class="note-list">
          <a-card
            v-for="note in classNotes"
            :key="note.id"
            class="note-card"
            @click="showModal(note)"
          >
            <template #title>
              <div class="note-title-center">
                <a @click.stop="goToVideo(note.outlineId)">{{ getNoteTitle(note.content) }}</a>
              </div>
            </template>
            <div class="markdown-preview-short">
              <MarkdownRenderer :markdown="note.content" :jumpToTime="noop" />
            </div>
            <div class="note-delete-btn">
              <a-popconfirm title="确定要删除该笔记吗？" ok-text="是" cancel-text="否" @confirm.stop="deleteNote(note.id)">
                <a-button type="text" shape="circle" danger @click.stop>
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </a-button>
              </a-popconfirm>
              <a-button type="link" @click.stop="editNote(note)">编辑</a-button>
              <a-button type="link" @click.stop="showShareModal(note)">分享</a-button>
            </div>
          </a-card>
        </div>
      </a-tab-pane>
      <a-tab-pane key="personal" tab="个人笔记">
        <div style="margin-bottom: 16px;">
          <a-button type="primary" @click="showAddModal">新建个人笔记</a-button>
        </div>
        <div class="note-list">
          <a-card
            v-for="note in personalNotes"
            :key="note.id"
            class="note-card"
            @click="showModal(note)"
          >
            <template #title>
              <div class="note-title-center">
                {{ getNoteTitle(note.content) }}
              </div>
            </template>
            <div class="markdown-preview-short">
              <MarkdownRenderer :markdown="note.content" :jumpToTime="noop" />
            </div>
            <div class="note-delete-btn">
              <a-popconfirm title="确定要删除该笔记吗？" ok-text="是" cancel-text="否" @confirm.stop="deletePersonalNote(note.id)">
                <a-button type="text" shape="circle" danger @click.stop>
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </a-button>
              </a-popconfirm>
              <a-button type="link" @click.stop="editNote(note)">编辑</a-button>
              <a-button type="link" @click.stop="showShareModal(note)">分享</a-button>
            </div>
          </a-card>
        </div>
      </a-tab-pane>
    </a-tabs>
    <!-- 全文模态框 -->
    <a-modal v-model:visible="modalVisible" width="60vw" :footer="null">
      <h2>{{ currentNoteTitle }}</h2>
      <MarkdownRenderer :markdown="currentNoteContent" :jumpToTime="noop" />
    </a-modal>
    <!-- 编辑modal -->
    <a-modal v-model:visible="editModalVisible" width="60vw" title="编辑笔记" @ok="saveEditNote">
      <MarkdownEditorPreview v-model="editContent" placeholder="请输入笔记内容..." :height="400" @ctrlS="saveEditNote" />
      <template #footer>
        <a-button @click="editModalVisible = false">取消</a-button>
        <a-button type="primary" @click="saveEditNote">保存</a-button>
      </template>
    </a-modal>
    <!-- 新建个人笔记modal -->
    <a-modal v-model:visible="addModalVisible" width="60vw" title="新建个人笔记" @ok="saveAddNote">
      <MarkdownEditorPreview v-model="addContent" placeholder="请输入笔记内容..." :height="400" @ctrlS="saveAddNote" />
      <template #footer>
        <a-button @click="addModalVisible = false">取消</a-button>
        <a-button type="primary" @click="saveAddNote">保存</a-button>
      </template>
    </a-modal>
    <!-- 分享modal -->
    <a-modal v-model:visible="shareModalVisible" width="70vw" :footer="null" :bodyStyle="{padding: '0', background:'#f8fafc'}">
      <div style="display:flex;flex-direction:column;height:80vh;">
        <div style="text-align:center; margin-bottom: 24px;">
          <span style="font-size:32px;color:#1677ff;vertical-align:middle;">
            <i class="anticon anticon-share-alt" style="margin-right:8px;"></i>
          </span>
          <span style="font-size: 2rem; font-weight: bold; color: #222; vertical-align: middle;">分享给队伍</span>
        </div>
        <div style="flex:1; min-height:0; overflow:auto; display: flex; flex-direction: column; align-items: center;">

          <div style="background: #fff; border-radius: 16px; box-shadow: 0 4px 24px rgba(22,119,255,0.08); padding: 24px 32px; width: 95%; max-width: 1100px; margin-bottom: 24px;">
<!--            <div style="max-height: 38vh; overflow: auto; border-radius: 8px; border: 1px solid #e5e7eb; background: #f6faff; padding: 16px;">-->
              <MarkdownRenderer :markdown="shareNote?.content || ''" :jumpToTime="noop" />
<!--            </div>-->
          </div>
          <div style="width: 95%; max-width: 1100px; margin-bottom: 24px;">
            <div style="font-size: 1.1rem; color: #888; margin-bottom: 8px; font-weight: 500;">帖子标题</div>
            <a-input v-model:value="inputTitle"></a-input>
          </div>
          <div style="width: 95%; max-width: 1100px; margin-bottom: 24px;">
            <div style="font-size: 1.1rem; color: #888; margin-bottom: 8px; font-weight: 500;">选择要分享的队伍</div>
            <a-select v-model:value="selectedTeamId" style="width: 100%;" placeholder="请选择队伍">
              <a-select-option v-for="team in teamList" :key="team.id" :value="team.id">
                <span style="display:flex;align-items:center;">
                  <a-avatar :size="28" :src="team.avatar" style="margin-right:8px;" />
                  <span>{{ team.name }}</span>
                </span>
              </a-select-option>
            </a-select>
          </div>
          <div style="text-align:center; color:#1677ff; font-size:1.1rem; margin-bottom: 12px;">
            “知识的价值在于分享，快把你的灵感传递给团队吧！”
          </div>
        </div>
        <div style="text-align:center; border-top:1px solid #e5e7eb; background:#f8fafc; padding: 18px 0 8px 0;">
          <a-button style="margin-right: 16px; min-width: 100px;" size="large" @click="shareModalVisible = false">取消</a-button>
          <a-button type="primary" size="large" style="min-width: 120px;" :disabled="!selectedTeamId" @click="handleShare">确认分享</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { DeleteOutlined } from '@ant-design/icons-vue'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'
import { getNotesByUser, saveNote, deleteDocById } from '@/api/bizMediaDocController.ts'
import { useRouter } from 'vue-router'
import { getOutlineById } from '@/api/bizCourseOutlinesController.ts'
import MarkdownEditorPreview from '@/components/MarkdownEditorPreview.vue'
import { addAuditTask } from '@/api/bizAuditTaskController.ts'
import { log } from 'echarts/types/src/util/log'
import { findJoinedTeams } from '@/api/sysTeamController.ts'
import { publish } from '@/api/bizPostController.ts'

const activeTab = ref('class')
const loading = ref(false)
const notes = ref<any[]>([])
const classNotes = ref<any[]>([])
const personalNotes = ref<any[]>([])
const modalVisible = ref(false)
const currentNoteTitle = ref('')
const currentNoteContent = ref('')
const noop = () => {}

const editModalVisible = ref(false)
const editContent = ref('')
const editingNote = ref<any>(null)

const addModalVisible = ref(false)
const addContent = ref('')

const shareModalVisible = ref(false)
const shareNote = ref<any>(null)
const selectedTeamId = ref<number|null>(null)
const teamList = ref([])
// 抽取markdown标题
function extractTitleFromMarkdown(markdown) {
  const match = markdown.trim().match(/^#\s+(.*)$/m)
  return match ? match[1] : ''
}

const inputTitle = ref('')

const fetchTeamList = async () => {
  const res = await findJoinedTeams()
  if (res.data.code == 0) {
    console.log('team', res.data.data)
    teamList.value = res.data.data?.map(team => {
      return {
        id: team.id,
        name: team.teamName,
        avatar: import.meta.env.VITE_PIC_BASE_URL + team.logo
      }
    })
  }
}

const router = useRouter()
const goToVideo = async (outlineId: number) => {
  if (!outlineId) return
  const res = await getOutlineById({ id: outlineId })
  if (res.data.code === 0 && res.data.data) {
    const courseId = res.data.data.courseId
    router.push(`/course/learn/${courseId}/${outlineId}`)
  }
}

const getNoteTitle = (content: string) => {
  if (!content) return '无标题'
  const firstLine = content.split('\n')[0].trim()
  if (firstLine.startsWith('#')) return firstLine.replace(/^#+/, '').trim() || '无标题'
  return firstLine || '无标题'
}

const showModal = (note: any) => {
  currentNoteTitle.value = getNoteTitle(note.content)
  currentNoteContent.value = note.content
  modalVisible.value = true
}

const editNote = (note: any) => {
  editingNote.value = note
  editContent.value = note.content
  editModalVisible.value = true
}

const saveEditNote = async () => {
  if (!editingNote.value) return
  const res = await saveNote({
    id: editingNote.value.id,
    content: editContent.value,
    outlineId: editingNote.value.outlineId,
    createBy: editingNote.value.createBy,
  })
  if (res.data.code === 0) {
    message.success('保存成功')
    editModalVisible.value = false
    fetchNotes()
  } else {
    message.error('保存失败')
  }
}

const showAddModal = () => {
  addContent.value = ''
  addModalVisible.value = true
}

const saveAddNote = async () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  const res = await saveNote({
    content: addContent.value,
    outlineId: null,
    createBy: userInfo.userId,
  })
  if (res.data.code === 0) {
    message.success('新建成功')
    addModalVisible.value = false
    fetchNotes()
  } else {
    message.error('新建失败')
  }
}

const deleteNote = async (id: number) => {
  const res = await deleteDocById({ id })
  if(res.data.code == 0) {
    message.success("删除笔记成功")
    fetchNotes()
  } else {
    message.error('删除笔记失败')
  }
}

const deletePersonalNote = async (id: number) => {
  const res = await deleteDocById({ id })
  if(res.data.code == 0) {
    message.success("删除个人笔记成功")
    fetchNotes()
  } else {
    message.error('删除个人笔记失败')
  }
}

const showShareModal = (note: any) => {
  shareNote.value = note
  selectedTeamId.value = null
  fetchTeamList()
  inputTitle.value = extractTitleFromMarkdown(note.content || '')
  shareModalVisible.value = true
}

const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const handleShare = async () => {
  shareModalVisible.value = false
  // console.log('params', params)
  const res = await publish({
    userId: userInfo.userId,
    teamId: selectedTeamId.value,
    title: inputTitle.value,
    content: shareNote.value.content,
    publishTime: new Date().getTime().toString(),
  })
  // console.log(res)
  if (res.data.code === 0) {
    message.success('已提交请求')
  } else {
    message.success('分享失败')
  }
}

const fetchNotes = async () => {
  try {
    loading.value = true
    const response = await getNotesByUser({
      createBy: userInfo.userId
    })
    notes.value = response.data.data || []
    classNotes.value = notes.value.filter((n: any) => n.outlineId)
    personalNotes.value = notes.value.filter((n: any) => !n.outlineId)
  } catch (error) {
    message.error('获取笔记失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchNotes()
  console.log('123', extractTitleFromMarkdown("# 标题"))
})
</script>

<style scoped>
.my-notes {
  padding: 24px;
}
.note-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.note-card {
  width: 350px;
  margin-bottom: 16px;
  transition: transform 0.25s cubic-bezier(.4,2,.6,1), box-shadow 0.25s cubic-bezier(.4,2,.6,1), z-index 0.25s;
  z-index: 1;
  cursor: pointer;
  position: relative;
}
.note-card:hover {
  transform: scale(1.01);
  box-shadow: 0 8px 32px rgba(0,0,0,0.18);
  z-index: 10;
}
.markdown-preview-short {
  max-height: 480px;
  overflow: hidden;
  position: relative;
}
.markdown-preview-short::after {
  content: '';
  position: absolute;
  left: 0; right: 0; bottom: 0;
  height: 32px;
  background: linear-gradient(to bottom, rgba(255,255,255,0), #fff 90%);
  pointer-events: none;
}
.note-title-center {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}
.note-delete-btn {
  position: absolute;
  right: 12px;
  bottom: 12px;
  z-index: 20;
}
</style>
